package com.howard.utils;

import java.lang.reflect.Array;

/**
 *
 * 数组工具类
 *
 * @author <a href="mailto:howard.he0329@gmail.com">Howard.He</a>
 *
 */
public final class ArrayUtils {

	private ArrayUtils() {
	}

	/**
	 * 将字符串数组转换成Integer型的数组
	 * 注意字符串数组必须为整型数字，否则出错 e.g new String[]{1,2,3}
	 * @param strArray 字符串数组
	 * @return Integer数组
	 */
	public static Integer[] convert(String[] strArray) {
		if(strArray == null || strArray.length == 0) {
			return null;
		}
		Integer[] array = new Integer[strArray.length];
		for(String str : strArray) {
			add(array, Integer.parseInt(str));
		}
		return array;
	}

	/**
	 * 数组中添加一个元素
	 * @param <T>
	 * @param array
	 * @param element
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T[] add(T[] array, T element) {
		Class<?> type;
		if(array != null) {
			type = array.getClass();
		} else if(element != null) {
			type = element.getClass();
		} else {
			throw new IllegalArgumentException("Arguments cannot both be null");
		}
		T[] newArray = null;
		if(array != null) {
			Object objArray = Array.newInstance(array.getClass().getComponentType(), array.length + 1);
			System.arraycopy(array, 0, objArray, 0, array.length);
			newArray = (T[])objArray;
		} else {
			newArray = (T[])Array.newInstance(type.getComponentType(), 1);
		}
		newArray[newArray.length -1] = element;
		return newArray;
	}
}
